package com.xindaoapp.happypet.activity;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.GoodsInfo;
import com.xindaoapp.happypet.bean.OrderDetail;
import com.xindaoapp.happypet.bean.OrderDetailEntity;
import com.xindaoapp.happypet.fragments.CheckstandFragment;
import com.xindaoapp.happypet.shop.ui.ProductDetailActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.ProgressHUD;

/**
 * 订单详情
 * 
 * @author Administrator
 */
public class MyOrderDetailActivity extends UMBaseActivity implements OnClickListener {
    private FrameLayout loading;
    private Context mContext;
    private ImageButton back;
    private TextView tv_title;

    private TextView order_state;
    private TextView order_ok;
    private TextView order_id;

    private TextView order_price;
    private TextView transpant_price;
    private LinearLayout order_content;// 分类

    private TextView name;
    private TextView phone;
    private TextView address;

    private TextView pay_way;
    private TextView peisong_way;

    private TextView cancle_order;

    private String orderId;
    private String flag;
    private String time;
    // private ProgressHUD progressHUD;

    private OrderDetail info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myorder_detail);
        mContext = MyOrderDetailActivity.this;
        orderId = getIntent().getStringExtra("orderID");
        flag = getIntent().getStringExtra("flag");
        time = getIntent().getStringExtra("time");

        initView();
        initData();
        getData();
    }

    private void initView() {
        loading = (FrameLayout) findViewById(R.id.loading);
        back = (ImageButton) findViewById(R.id.cancel);
        tv_title = (TextView) findViewById(R.id.title);

        order_state = (TextView) findViewById(R.id.order_detail_state);
        order_ok = (TextView) findViewById(R.id.order_detail_ok);
        order_id = (TextView) findViewById(R.id.order_detail_id);

        order_price = (TextView) findViewById(R.id.order_detail_total_price);
        transpant_price = (TextView) findViewById(R.id.order_detail_transpant_price);
        order_content = (LinearLayout) findViewById(R.id.order_detail_content);

        name = (TextView) findViewById(R.id.order_detail_username);
        phone = (TextView) findViewById(R.id.order_detail_phone);
        address = (TextView) findViewById(R.id.order_detail_address);

        pay_way = (TextView) findViewById(R.id.order_detail_pay_way);
        peisong_way = (TextView) findViewById(R.id.order_detail_peisong_way);

        cancle_order = (TextView) findViewById(R.id.order_detail_cancle_order);

        switch (Integer.parseInt(flag)) {
            case 1:
                tv_title.setText("待付款订单");
                cancle_order.setVisibility(View.VISIBLE);
                cancle_order.setEnabled(true);
                break;
            case 2:
                tv_title.setText("待发货订单");
                cancle_order.setVisibility(View.GONE);
                cancle_order.setEnabled(false);
                break;
            case 3:
                tv_title.setText("待收货订单");
                cancle_order.setVisibility(View.GONE);
                cancle_order.setEnabled(false);
                break;
            case 4:
                tv_title.setText("已完成订单");
                cancle_order.setVisibility(View.VISIBLE);
                cancle_order.setText("申请退款");
                cancle_order.setEnabled(true);
                break;
        }
    }

    private void initData() {
        back.setOnClickListener(this);
        order_ok.setOnClickListener(this);
        cancle_order.setOnClickListener(this);
    }

    private void getData() {
        if (CommonUtil.checkNetState(mContext)) {
            RequestParams params = new RequestParams();
            params.put("orderID", CommonUtil.decode(orderId));
            params.put("userID", CommonUtil.decode(UserState.getUserUid()));
            params.add("version", "1.0");

            // progressHUD = ProgressHUD.show(mContext, "正在加载...", true, true, null);
            AddClient.get(Address.ORDER_DETAIL, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    OrderDetailEntity entity = null;

                    try {
                        entity = JSON.parseObject(content, OrderDetailEntity.class);
                        if (null == entity) {
                            Toast.makeText(mContext, R.string.get_error_data, 0).show();
                            return;
                        }
                        OrderDetail product = entity.data;

                        if (null == product) {
                            Toast.makeText(mContext, R.string.get_error_data, 0).show();
                            return;
                        }
                        info = product;
                        initMyData(product);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFinish() {
                    /*
                     * if (null != progressHUD && progressHUD.isShowing()) { progressHUD.dismiss();
                     * }
                     */
                    if (loading != null && loading.getVisibility() == View.VISIBLE) {
                        loading.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    super.onFailure(error, content);
                }
            });
        } else {
            Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
            return;
        }
    }

    private String totalprice;

    private void initMyData(OrderDetail order) {
        order_ok.setVisibility(View.VISIBLE);
        switch (order.order_info.type_status) {
            case 1:
                tv_title.setText("待付款订单");
                order_state.setText("订单状态:" + "待付款");
                order_state.setText(changeTextColor(order_state, 5, 3, "#D95234"));
                order_ok.setText("马上付款");
                cancle_order.setVisibility(View.VISIBLE);
                break;
            case 2:
                tv_title.setText("待发货订单");
                order_state.setText("订单状态:" + "待发货");
                order_state.setText(changeTextColor(order_state, 5, 3, "#D95234"));
                order_ok.setVisibility(View.GONE);
                cancle_order.setVisibility(View.GONE);
                break;
            case 3:
                tv_title.setText("待收货订单");
                order_state.setText("订单状态:" + "待收货");
                order_state.setText(changeTextColor(order_state, 5, 3, "#D95234"));
                order_ok.setText("确认收货");
                cancle_order.setVisibility(View.GONE);
                break;
            case 4:
                tv_title.setText("已完成订单");
                order_state.setText("订单状态:" + "已完成");
                order_state.setText(changeTextColor(order_state, 5, 3, "#D95234"));

                if (order.goods_info.get(0).is_commented == 0) {
                    order_ok.setText("评价");
                } else {
                    order_ok.setVisibility(View.GONE);
                }
                cancle_order.setVisibility(View.VISIBLE);
                cancle_order.setText("申请退款");
                break;
        }

        order_id.setText("订单号:" + order.order_info.order_sn);
        order_id.setText(changeTextColor(order_id, 4, order.order_info.order_sn.length(), "#666666"));
        order_price.setText("￥"
                + CommonUtil.transitionToFloat(order.order_info.order_amount
                        - order.order_info.shipping_fee));
        transpant_price.setText("￥" + CommonUtil.transitionToFloat(order.order_info.shipping_fee));

        ((TextView) findViewById(R.id.order_detail_transpant_price_total)).setText("￥"
                + CommonUtil.transitionToFloat(order.order_info.order_amount));

        totalprice = CommonUtil.transitionToFloat(order.order_info.order_amount);

        name.setText("收货人:" + order.shipping_info.name);
        name.setText(changeTextColor(name, 4, order.shipping_info.name.length(), "#666666"));
        phone.setText(order.shipping_info.mobile);
        address.setText(order.shipping_info.address);
        // address.setText(changeTextColor(address, 3, order.shipping_info.address.length(),
        // "#666666"));

        pay_way.setText("支付方式:" + "在线支付");
        pay_way.setText(changeTextColor(pay_way, 5, 4, "#666666"));
        peisong_way.setText("配送方式:" + "快递");
        peisong_way.setText(changeTextColor(peisong_way, 5, 2, "#666666"));

        preparOrderContent(order.goods_info);
        /*
         * loading.setVisibility(View.GONE); if (null != progressHUD && progressHUD.isShowing()) {
         * progressHUD.dismiss(); }
         */
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_detail_ok:// 红色按钮
                if (order_ok.getText().toString().equals("评价")) {
                    if (info.goods_info.size() == 1) {
                        if (info.goods_info.get(0).is_commented == 0) {
                            Intent intent =
                                    new Intent(MyOrderDetailActivity.this,
                                            OrderEvaluateActivity.class);
                            intent.putExtra("object", info.goods_info.get(0));
                            intent.putExtra("time", time);
                            startActivity(intent);
                        } else {
                            Toast.makeText(mContext, "商品已经评价过！", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Intent intent =
                                new Intent(MyOrderDetailActivity.this, EvaluateActivity.class);
                        intent.putExtra("time", time);
                        intent.putExtra("list", info.goods_info);
                        startActivity(intent);
                    }
                    finish();
                } else if (order_ok.getText().toString().equals("确认收货")) {
                    sureHaveGot();
                } else if (order_ok.getText().toString().equals("马上付款")) {
                    Intent intent = new Intent(MyOrderDetailActivity.this, MainActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putFloat(Constants.KEY_ORDER_TOTAL_PRICE, info.order_info.order_amount);
                    bundle.putString(Constants.KEY_ORDER_NUMBER, info.order_info.order_sn);
                    bundle.putString(Constants.KEY_ORDER_TITLE, info.goods_info.get(0).goods_name);
                    intent.putExtra(Constants.KEY_BUNDLE, bundle);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            CheckstandFragment.class.getCanonicalName());
                    startActivity(intent);
                }
                break;
            case R.id.order_detail_cancle_order:// 取消订单
                if (cancle_order.getText().toString().trim().equals("取消订单")) {
                    new AlertDialog.Builder(MyOrderDetailActivity.this).setTitle("取消订单")
                            .setMessage("确定要取消订单吗?")
                            .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    cancleOrder();
                                    dialog.dismiss();
                                }
                            }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {}
                            }).create().show();
                } else if (cancle_order.getText().toString().trim().equals("申请退款")) {
                    Intent intent = new Intent(mContext, PayBackActivity.class);
                    intent.putExtra("orderId", orderId);
                    intent.putExtra("price", totalprice);
                    startActivity(intent);
                }

                break;
            case R.id.cancel:
                finish();
                break;
            default:
                break;
        }
    }

    private void sureHaveGot() {
        if (CommonUtil.checkNetState(mContext)) {
            RequestParams params = new RequestParams();
            params.put("userID", CommonUtil.decode(UserState.getUserUid()));
            params.put("orderID", CommonUtil.decode(orderId));
            params.add("version", "1.0");

            final ProgressHUD progressHUD = ProgressHUD.show(mContext, "正在加载...", true, true, null);
            AddClient.get(Address.SUREHAVEGOT, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    if (null != progressHUD && progressHUD.isShowing()) {
                        progressHUD.dismiss();
                    }
                    int status = -1;
                    JSONObject obj;
                    try {
                        obj = new JSONObject(content);
                        status = obj.getInt("status");

                        if (status == 1) {
                            Toast.makeText(mContext, "确认成功!", Toast.LENGTH_SHORT).show();
                            sendBroadcast(new Intent(Constants.ORDER_DETAIL));
                            // order_ok.setText("去评价");
                            getData();
                        } else {
                            Toast.makeText(mContext, "确认失败!", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    if (null != progressHUD && progressHUD.isShowing()) {
                        progressHUD.dismiss();
                    }
                    super.onFailure(error, content);
                }
            });
        } else {
            Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
            return;
        }
    }

    private void cancleOrder() {
        if (CommonUtil.checkNetState(mContext)) {
            RequestParams params = new RequestParams();
            params.put("userID", CommonUtil.decode(UserState.getUserUid()));
            params.put("orderID", CommonUtil.decode(orderId));
            params.add("version", "1.0");

            final ProgressHUD progressHUD = ProgressHUD.show(mContext, "正在加载...", true, true, null);
            AddClient.get(Address.CANCEL_ORDER, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    if (null != progressHUD && progressHUD.isShowing()) {
                        progressHUD.dismiss();
                    }
                    int status = -1;
                    JSONObject obj;
                    try {
                        obj = new JSONObject(content);
                        status = obj.getInt("status");
                        if (status == 1) {
                            Toast.makeText(mContext, "取消成功!", Toast.LENGTH_SHORT).show();
                            sendBroadcast(new Intent(Constants.ORDER_DETAIL));
                            finish();
                        } else {
                            Toast.makeText(mContext, "取消失败!", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    if (null != progressHUD && progressHUD.isShowing()) {
                        progressHUD.dismiss();
                    }
                    super.onFailure(error, content);
                }
            });
        } else {
            Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
            return;
        }
    }

    private void preparOrderContent(final List<GoodsInfo> info) {
        order_content.removeAllViews();
        for (int i = 0; i < info.size(); i++) {
            View view = View.inflate(mContext, R.layout.common_order_product_infor, null);
            ImageView icon = (ImageView) view.findViewById(R.id.order_icon);
            TextView title = (TextView) view.findViewById(R.id.order_title);
            TextView category = (TextView) view.findViewById(R.id.order_category);
            TextView num = (TextView) view.findViewById(R.id.order_num);
            TextView price = (TextView) view.findViewById(R.id.order_price);
            View line = view.findViewById(R.id.line);

            num.setText("×" + info.get(i).goods_number);
            num.setText(changeTextColor(num, 1, String.valueOf(info.get(i).goods_number).length(),
                    "#D95234"));
            ImageLoader.getInstance().displayImage(info.get(i).goods_thumb, icon);
            title.setText(info.get(i).goods_name);
            category.setText("分类:" + info.get(i).cat_name);
            price.setText("￥" + String.valueOf(info.get(i).goods_price));

            if (i == info.size() - 1) {
                line.setVisibility(View.GONE);
            }

            final int j = i;
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent intent =
                            new Intent(MyOrderDetailActivity.this, ProductDetailActivity.class);
                    intent.putExtra(Constants.KEY_GOODS_ID, info.get(j).goods_id);
                    startActivity(intent);


                    // Intent intent =
                    // new Intent(MyOrderDetailActivity.this, ProductDetailActivity1.class);
                    // intent.putExtra("productId", info.get(j).goods_id);
                    // startActivity(intent);
                }
            });
            order_content.addView(view);
        }
    }

    private SpannableStringBuilder changeTextColor(TextView tv, int start, int end, String color) {
        SpannableStringBuilder builder = new SpannableStringBuilder(tv.getText().toString());
        ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.parseColor(color));
        builder.setSpan(redSpan, start, start + end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return builder;
    }

}
